import React, { Component } from 'react'
import { Layout } from 'antd'
import { Menu, Icon } from 'antd'
import './index.less'
import logo from '@/assets/images/logo.png'
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
const { Sider } = Layout
const { SubMenu } = Menu

@connect(
  (state) => ({ title: state.title }),
  (dispatch) => ({
    setTtile: (titleName) => dispatch({ type: 'setTitle', data: titleName }),
  })
)
class Left extends Component {
  state = {
    collapsed: false,
    openKeys: [],
  }

  onCollapse = (collapsed) => {
    this.setState({ collapsed })
  }

  clickMenu = (titleName) => {
    this.props.setTtile(titleName)
  }

  render() {
    return (
      <Sider
        breakpoint="lg"
        className="left"
        collapsible
        collapsed={this.state.collapsed}
        onCollapse={this.onCollapse}
      >
        <div className="left-header">
          <img src={logo}></img>
          <span>REACT后台</span>
        </div>
        <Menu
          defaultSelectedKeys={[
            /(\/[a-zA-Z]*\/[a-zA-Z]*)/.exec(this.props.location.pathname)
              ? /(\/[a-zA-Z]*\/[a-zA-Z]*)/.exec(this.props.location.pathname)[0]
              : this.props.location.pathname,
          ]}
          defaultOpenKeys={[
            /(\/[a-zA-Z]*)/.exec(this.props.location.pathname)[0],
          ]}
          mode="inline"
          theme="dark"
        >
          {this.props.menus.map((item) => {
            if (item.children) {
              return (
                <SubMenu
                  key={item.path}
                  title={
                    <span>
                      <Icon type={item.icon} />
                      <span>{item.title}</span>
                    </span>
                  }
                >
                  {item.children.map((child) => {
                    return (
                      <Menu.Item key={child.path}>
                        <Link
                          to={child.path}
                          onClick={() => this.clickMenu(child.title)}
                        >
                          <Icon type={child.icon} />
                          <span>{child.title}</span>
                        </Link>
                      </Menu.Item>
                    )
                  })}
                </SubMenu>
              )
            } else {
              return (
                <Menu.Item key={item.path}>
                  <Link
                    to={item.path}
                    onClick={() => this.clickMenu(item.title)}
                  >
                    <Icon type={item.icon} />
                    <span>{item.title}</span>
                  </Link>
                </Menu.Item>
              )
            }
          })}
        </Menu>
      </Sider>
    )
  }
}
export default Left
